package com.globussoft.amazons3;

import com.globussoft.xml.CreatXMLFile;
import com.globussoft.xml.SettingsXml;
import com.cloudminga.database.DataBaseHelper;
import com.cloudminga.gui.MainDialog;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.globussoft.util.*;
import com.cloudminga.gui.RestoreProgressBar;
import org.jets3t.service.model.S3Bucket;

/**
 *
 * @author Globussoft
 */
public class UploadFile {

    AmazonS3Utility amazons3S3Utility;
    static private HashMap fileIndex;
    CreatXMLFile createXMLFile;
    DataBaseHelper databaseHelper;
    private static int totalFilesUploaded;
    private static boolean uploadContinue = true;
    private static int filesTransfer = 0;
    private static long sizeTransfer = 0;
    private    RestoreProgressBar restore;

    public static long getSizeTransfer()
    {
        return sizeTransfer;
    }
    public static int getFileTransfer()
    {
        return filesTransfer;
    }
    public static void setFileIndex(HashMap map)
    {
        fileIndex=map;
    }
    public static HashMap getFileIndex()
    {
        return fileIndex;
    }
    public static void setUploadContinue(boolean setTo) {
        uploadContinue = setTo;
    }

    public UploadFile() {
        amazons3S3Utility = new AmazonS3Utility();
        createXMLFile = new CreatXMLFile();
        databaseHelper = new DataBaseHelper();
        restore = new RestoreProgressBar();
    }

    public String generateUniqeKey() {
        Date date = new Date();
        return "" + date.getYear() + date.getMonth() + date.getDay() + date.getHours() + date.getMinutes() + date.getSeconds() + date.getTime();
    }

    public void downloadMainIndexFile(String username) {
        amazons3S3Utility.DownloadFile(username, "Index.txt");
        try {
            ObjectInputStream objin = new ObjectInputStream(new FileInputStream("Index.txt"));
            fileIndex = (HashMap) objin.readObject();
            objin.close();
            deleteMainIndexFile();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(UploadFile.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(UploadFile.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void uploadMainIndexFile(String username) {
        try {
            ObjectOutputStream object = new ObjectOutputStream(new FileOutputStream("Index.txt"));
            object.writeObject(fileIndex);
            object.close();
            amazons3S3Utility.UploadFile("Index.txt", username);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        deleteMainIndexFile();
    }

    private void deleteMainIndexFile() {
        try {
            File f = new File("Index.txt");
            f.delete();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    // This Method uploads files that are stored on the HashMap
    public void uploadFiles(String path, String From, int totalNmberOfFiles, long downloadStartTime) //Uploads Files
    {
        System.out.println("fileindex" + fileIndex + "  " + Thread.currentThread().getName());        
       
        String username = SettingsXml.getUser().replace("@", ".");
        if (!From.equals("Manual")) {
            restore.setVisible(true);
        }
        MainDialog.UpDownProgressBar.setVisible(true);
        MainDialog.UpDownProgressBar.setValue(0);
        String email = SettingsXml.getUser();
        // Object[] filesToStore = map.keySet().toArray();
        String filesToStore = "";
        java.sql.Timestamp t = null;
        java.sql.Timestamp t1 = null;

    
        long duration = 0;
        //int counter = 0;

        try {
            while (MultithreadingUpload.getQueueSize() > 0 && uploadContinue) {
                Object[] obj = null;
                synchronized (this) {
                    obj = MultithreadingUpload.getFileNameFromQueue();
                    filesToStore = obj[0].toString();
                    System.out.println("Thread  " + Thread.currentThread().getName() + " Getting " + filesToStore);
                }

                t1 = null;
                if (obj[1].toString().equals("false")) {
                    String directoryName = filesToStore.substring(0, filesToStore.replace("\\", "/").lastIndexOf("/"));
                    String filename = filesToStore.substring(filesToStore.replace("\\", "/").lastIndexOf("/") + 1);
                    boolean dirExistOnTheHashMap = false;
                    S3Bucket s3bucket = null;
                    synchronized (this) {
                        dirExistOnTheHashMap = fileIndex.containsKey(directoryName.toLowerCase().trim().replace("\\", "/"));
                        if (!dirExistOnTheHashMap) {
                            String uniqukey = generateUniqeKey();
                            s3bucket = amazons3S3Utility.CreateBucket(username + "." + uniqukey);
                            fileIndex.put(directoryName.toLowerCase().trim().replace("\\", "/"), username + "." + uniqukey);
                        }
                    }
                    String s333 = fileIndex.get(directoryName.toLowerCase().trim().replace("\\", "/")).toString();
                    System.out.println(s333);
                    if (!databaseHelper.checkFileExist(email, directoryName + "/" + filename)) {
                        t = new java.sql.Timestamp(new java.util.Date().getTime());
                        amazons3S3Utility.UploadFile(filesToStore, s333);
                        filesTransfer++;
                        sizeTransfer += new File(directoryName + "/" + filename).length();
                        t1 = new java.sql.Timestamp(new java.util.Date().getTime());
                        createXMLFile.changeXmlStatusNode(path, filesToStore, true);
                        System.out.println("Uploading of " + filename + "  is completed");
                        //uploadMainIndexFile(username);
                        if (From.equals("Manual")) {
                            MainDialog.UpDownProgressBar.setValue((100 * (totalFilesUploaded + 1) / totalNmberOfFiles));
                        } else {
                            RestoreProgressBar.RestoreProgressBar.setValue((100 * (totalFilesUploaded + 1) / totalNmberOfFiles));
                        }
                        totalFilesUploaded++;
                        databaseHelper.insertIntoBackupDetailTb(email, downloadStartTime, filesToStore, (t1.getTime() - t.getTime()), "");
                    } else {
                        databaseHelper.insertIntoBackupDetailTb(email, downloadStartTime, filesToStore, 0, "File Allready Exist On the Server");
                    }
//                    if (t1 == null) {
//                        databaseHelper.insertIntoBackupDetailTb(email, startTime, filesToStore, 0, "File Allready Exist On the Server");
//                    } else {
//                        databaseHelper.insertIntoBackupDetailTb(email, startTime, filesToStore, (t1.getTime() - t.getTime()), "");
//                        duration += (t1.getTime() - t.getTime());
//                    }
                }

                // }
//            if (From.equals("Manual")) {
//                MainDialog.UpDownProgressBar.setVisible(false);
//                MainDialog.ProgressLevel.setVisible(false);
//                MainDialog.but_start.setText("Start Backup");
//            } else {
//                RestoreProgressBar.RestoreProgressBar.setVisible(false);
//                RestoreProgressBar.RestoreProgressLabel.setText("Uploading Completed");
//                restore.setVisible(false);
//            }
//
//            int totalfiles = 0;
//            long selectedFilesSize = 0;
//            if (MainForm.getSelectionButton().equals("filesystemButton")) {
//                if (TestFileTree.getSelectedNodes() != null) {
//                    totalfiles = TestFileTree.getSelectedNodes().size();
//                }
//                selectedFilesSize = TestFileTree.getSelectedFilesSize();
//            } else {
//                totalfiles = MainForm.getBackupSetSelectedFiles();
//                selectedFilesSize = MainForm.getBackupSetSelectedFiles();
//            }
//            if (uploadContinue) {
//                if (totalNmberOfFiles != 0) {
//                    if (From.equals("Manual")) {
//                        databaseHelper.insertIntoBackupTb(email, MachineName, MacId, IPAddress, startTime, type, duration, "Sucessful", totalNmberOfFiles, sizeTransfer, filesTransfer, sizeTransfer);
//                    } else {
//                        databaseHelper.insertIntoBackupTb(email, MachineName, MacId, IPAddress, startTime, "Automatic", duration, "Sucessful", totalNmberOfFiles, sizeTransfer, filesTransfer, sizeTransfer);
//                    }
//                }
//            } else {
//                if (totalNmberOfFiles != 0) {
//                    if (From.equals("Manual")) {
//                        databaseHelper.insertIntoBackupTb(email, MachineName, MacId, IPAddress, startTime, type, duration, "Cancle", totalNmberOfFiles, selectedFilesSize, filesTransfer, sizeTransfer);
//                    } else {
//                        databaseHelper.insertIntoBackupTb(email, MachineName, MacId, IPAddress, startTime, "Automatic", duration, "Cancle", totalNmberOfFiles, Config_3_backup.usedSize, filesTransfer, sizeTransfer);
//                    }
//               }
//            }
            }
            //       AmazonS3Utility.setFileTransfer(0);
            //       AmazonS3Utility.setSizeTransfer(0);
        } catch (Exception ex) {
            //  ex.printStackTrace();
        } finally {
        }
    }

    public void downloadFile(HashMap map, String pathToStoreDownloadedFile, boolean renameIfFileExist) {
        downloadMainIndexFile(SettingsXml.getUser().replace("@", "."));
        Object[] obj = map.keySet().toArray();
        int len = obj.length;
        long startTime = new java.util.Date().getTime();
        int i = 0;
        RestoreProgressBar restoreProgreeBar = new RestoreProgressBar();
        restoreProgreeBar.setVisible(true);
        for (i = 0; i < len; i++) {
            try {
                RestoreProgressBar.RestoreProgressBar.setValue((i) * 100 / len);
//                RestoreProgressBar.RestoreProgressLabel.setText("Downloading  " + obj[i].toString());
                String bucketname = fileIndex.get(obj[i].toString().substring(0, obj[i].toString().trim().replace("\\", "/").lastIndexOf("/")).toLowerCase()).toString();
                amazons3S3Utility.DownloadFile(bucketname, obj[i].toString(), pathToStoreDownloadedFile, renameIfFileExist, startTime, SettingsXml.getUser(), "Restore");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        RestoreProgressBar.RestoreProgressBar.setValue(100);
//        RestoreProgressBar.RestoreProgressLabel.setText("Downloading  Completed");
        MainDialog.UpDownProgressBar.setVisible(false);
        long endTime = new java.util.Date().getTime();
        if (i == len && i != 0) {
            databaseHelper.insertIntoBackupTb(SettingsXml.getUser(), ComputerNameAndAddress.getComputerName(), MacAddress.getMacAddress(), ComputerNameAndAddress.getIPAddress(), startTime, "Restore", (endTime - startTime), "Sucessful", AmazonS3Utility.getFileTransfer(), AmazonS3Utility.getSizeTransfer(), AmazonS3Utility.getFileTransfer(), AmazonS3Utility.getSizeTransfer());
        }
        AmazonS3Utility.setFileTransfer(0);
        AmazonS3Utility.setSizeTransfer(0);
    }

    public static void main(String[] arg) {
        try {
            UploadFile upload = new UploadFile();
            HashMap map = new HashMap();
            map.put("C:/index.txt", "d:");
            upload.downloadFile(map, "D:", false);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
